package com.htudata.transctLive.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;

import com.htudata.alarm.pojo.po.AlarmLevelPO;
import com.htudata.alarm.service.AlarmLevelService;
import com.htudata.common.service.TokenService;
import com.htudata.core.util.IpUtils;
import com.htudata.core.util.operation.*;
import com.htudata.history.service.HisService;
import com.htudata.item.service.ItemSelectService;
import com.htudata.live.pojo.vo.AlarmStatisVO;
import com.htudata.live.pojo.vo.ItemStatisVO;
import com.htudata.node.service.impl.NodeShowService;
import com.htudata.transctAlarm.service.TransctAlarmLevelService;
import com.htudata.transctAlarm.service.TransctAlarmShowService;
import com.htudata.transctFlow.dao.TransctFlowDao;
import com.htudata.transctLive.dao.TransctLiveDao;
import com.htudata.transctLive.pojo.vo.TransctFlowGraphicDisplayVo;
import com.htudata.transctLive.pojo.vo.TransctFlowVO;
import com.htudata.transctLive.pojo.vo.TransctLinkVO;
import com.htudata.transctLive.pojo.vo.TransctNodeVO;
import com.htudata.transctLive.service.TransctFlowService;
import com.htudata.transctNode.service.TransctLinkService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TransctFlowServiceImpl implements TransctFlowService {

  @Autowired
  private ItemSelectService itemSelectService;
  
  @Autowired
  private HisService hisService;
  
  @Autowired
  private TransctAlarmShowService alarmShowService;
  
  @Autowired
  private TransctAlarmLevelService alarmLevelService;
  
  @Autowired
  private TransctLinkService linkService;
  
  @Autowired
  private TransctLiveDao liveDao;
  
  @Autowired
  private TransctFlowDao flowDao;
  
  @Autowired
  private HttpServletRequest request;
  
  @Value("${show_default_value}")
  private String show_default_value;
  
  @Value("${item_value_decimal}")
  private int item_value_decimal;
  
  @Value("${get_item_value_frequency}")
  private int get_item_value_frequency;
  
  @Value("${recover_time_range}")
  private int recover_time_range;
  
  @Value("${virtual_station}")
  private int VIRTUALSTATION;
  
  public List<TransctFlowVO> getVOList(String... dataTypeIds) {
    List<TransctFlowVO> flowVOList = new ArrayList<>();
    return flowVOList;
  }

  @Override
  public JSONObject getFlowGraphicDisplayVoList3(int alarm, int statis, int nodeTypeId, int page, int perPage, int stationTypeId, String a2) throws Exception {
    return getFlowGraphicDisplayVoList4(alarm, statis, nodeTypeId, page, perPage, stationTypeId, a2, "", "");
  }

  @Override
  public JSONObject getFlowGraphicDisplayVoList4(int alarm, int statis, int nodeTypeId, int page, int perPage, int stationTypeId, String a2, String flowName, String nodeNickName) throws Exception {
    List<Map<String, Object>> selectFlowsAndNodesByFlowId = this.liveDao.selectFlowsAndNodesByFlowId3(null, nodeTypeId, 
        NodeShowService.getChildNodeTypeId(nodeTypeId), stationTypeId, null, flowName, nodeNickName);
    List<Map<String, Object>> flowAndNodeList = (List<Map<String, Object>>)selectFlowsAndNodesByFlowId.get(0);
    List<TransctFlowGraphicDisplayVo> flowGraphicVoList = new ArrayList<>();
    handleFlowGraphicDisplayVoList(flowAndNodeList, flowGraphicVoList);
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList(a2);
    if (alarm == 1)
      setNodeAlarms(flowGraphicVoList, "-1", false, a2, alarmLevelList); 
    JSONObject result = new JSONObject();
    result.put("data", Collections.EMPTY_LIST);
    if (CollectionsOperationUtils.isValidCollection(flowGraphicVoList)) {
      JSONArray flowGraphicVoList1 = new JSONArray();
      JSONObject flowGraphicDisplayVo1 = null;
      JSONArray nodeList = null;
      JSONObject node = null;
      for (int i = 0, length = flowGraphicVoList.size(); i < length; i++) {
        flowGraphicDisplayVo1 = new JSONObject();
        flowGraphicDisplayVo1.put("dataTypeId", Long.valueOf(((TransctFlowGraphicDisplayVo)flowGraphicVoList.get(i)).getDataTypeId()));
        flowGraphicDisplayVo1.put("flowId", ((TransctFlowGraphicDisplayVo)flowGraphicVoList.get(i)).getFlowId());
        flowGraphicDisplayVo1.put("name", ((TransctFlowGraphicDisplayVo)flowGraphicVoList.get(i)).getName());
        nodeList = new JSONArray();
        for (int j = 0, length2 = ((TransctFlowGraphicDisplayVo)flowGraphicVoList.get(i)).getNodes().size(); j < length2; j++) {
          node = new JSONObject();
          node.put("nodeId", ((TransctNodeVO)((TransctFlowGraphicDisplayVo)flowGraphicVoList.get(i)).getNodes().get(j)).getNodeId());
          node.put("name", ((TransctNodeVO)((TransctFlowGraphicDisplayVo)flowGraphicVoList.get(i)).getNodes().get(j)).getNickName());
          nodeList.add(node);
          int k = 0;
          for (int length3 = ((TransctNodeVO)((TransctFlowGraphicDisplayVo)flowGraphicVoList.get(i)).getNodes().get(j)).getChildren().size(); k < length3; k++) {
            node = new JSONObject();
            node.put("nodeId", ((TransctNodeVO)((TransctNodeVO)((TransctFlowGraphicDisplayVo)flowGraphicVoList.get(i)).getNodes().get(j)).getChildren().get(k)).getNodeId());
            node.put("name", ((TransctNodeVO)((TransctNodeVO)((TransctFlowGraphicDisplayVo)flowGraphicVoList.get(i)).getNodes().get(j)).getChildren().get(k)).getNickName());
            nodeList.add(node);
          } 
        } 
        flowGraphicDisplayVo1.put("nodes", nodeList);
        flowGraphicVoList1.add(flowGraphicDisplayVo1);
      } 
      result.put("data", flowGraphicVoList1);
    } 
    return result;
  }

  @Override
  public JSONObject getFlowGraphicDisplayVoList2(int alarm, int statis, int nodeTypeId, int page, int perPage, int stationTypeId, String a2) throws Exception {
    List<Long> userIds = null;
    long roleType = TokenService.getRoleType(this.request);
    if (roleType != -1L && roleType != 1L) {
      userIds = new ArrayList<>();
      userIds.add(Long.valueOf(TokenService.getUserId(this.request)));
    } 
    List<Map<String, Object>> selectAllFlowsAndNodesByFlowId = this.liveDao.selectAllFlowsAndNodesByFlowId2(null, nodeTypeId, 
        NodeShowService.getChildNodeTypeId(nodeTypeId), stationTypeId, userIds, getRowIndex(page, perPage), perPage);
    List<Map<String, Object>> selectFlowsAndNodesByFlowId = this.liveDao.selectFlowsAndNodesByFlowId2(null, nodeTypeId, 
        NodeShowService.getChildNodeTypeId(nodeTypeId), stationTypeId, userIds, getRowIndex(page, perPage), perPage);
    List<Map<String, Object>> flowAndNodeList = (List<Map<String, Object>>)selectFlowsAndNodesByFlowId.get(0);
    List<TransctFlowGraphicDisplayVo> flowGraphicVoList = new ArrayList<>();
    handleFlowGraphicDisplayVoListNew(flowAndNodeList, flowGraphicVoList, nodeTypeId, selectAllFlowsAndNodesByFlowId);
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList(a2);
    if (alarm == 1)
      setNodeAlarms(flowGraphicVoList, "-1", false, a2, alarmLevelList); 
    JSONObject result = new JSONObject();
    result.put("data", Collections.EMPTY_LIST);
    result.put("page", Integer.valueOf(page));
    result.put("perPage", Integer.valueOf(perPage));
    result.put("total", Integer.valueOf(0));
    if (CollectionsOperationUtils.isValidCollection(flowGraphicVoList)) {
      TransctFlowGraphicDisplayVo flowGraphicDisplayVo1 = new TransctFlowGraphicDisplayVo();
      for (int i = 0, length = flowGraphicVoList.size(); i < length; i++)
        flowGraphicDisplayVo1.getNodes().addAll(((TransctFlowGraphicDisplayVo)flowGraphicVoList.get(i)).getNodes()); 
      sortNodesBylevel(flowGraphicDisplayVo1.getNodes(), "desc");
      List<TransctFlowGraphicDisplayVo> flowGraphicVoList1 = new ArrayList<>();
      flowGraphicVoList1.add(flowGraphicDisplayVo1);
      result.put("data", flowGraphicVoList1);
    } 
    result.put("total", ((HashMap)((ArrayList<HashMap>)selectFlowsAndNodesByFlowId
        .get(1)).get(0))
        .get("total"));
    return result;
  }

  @Override
  public JSONObject getFlowGraphicDisplayVoListV2(int alarm, int statis, int nodeTypeId, int page, int perPage, int level, int stationTypeId, String a2) throws Exception{
    List<Long> userIds = null;
    long roleType = TokenService.getRoleType(this.request);
    if (roleType != -1L && roleType != 1L) {
      userIds = new ArrayList<>();
      userIds.add(Long.valueOf(TokenService.getUserId(this.request)));
    } 
    List<Map<String, Object>> selectAllFlowsAndNodesByFlowId = this.liveDao.selectAllFlowsAndNodesByFlowId2(null, nodeTypeId, 
        NodeShowService.getChildNodeTypeId(nodeTypeId), stationTypeId, userIds, getRowIndex(page, perPage), perPage);
    List<Map<String, Object>> selectFlowsAndNodesByFlowId = this.liveDao.selectFlowsAndNodesByFlowIdV2(null, nodeTypeId, 
        NodeShowService.getChildNodeTypeId(nodeTypeId), stationTypeId, userIds, getRowIndex(page, perPage), perPage);
    List<Map<String, Object>> flowAndNodeList = (List<Map<String, Object>>)selectFlowsAndNodesByFlowId.get(0);
    List<TransctFlowGraphicDisplayVo> flowGraphicVoList = new ArrayList<>();
    handleFlowGraphicDisplayVoListNew(flowAndNodeList, flowGraphicVoList, nodeTypeId, selectAllFlowsAndNodesByFlowId);
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList(a2);
    if (alarm == 1)
      setNodeAlarmsV2(flowGraphicVoList, "-1", false, a2, alarmLevelList, level); 
    JSONObject result = new JSONObject();
    result.put("data", Collections.EMPTY_LIST);
    result.put("page", Integer.valueOf(page));
    result.put("perPage", Integer.valueOf(perPage));
    if (CollectionsOperationUtils.isValidCollection(flowGraphicVoList)) {
      TransctFlowGraphicDisplayVo flowGraphicDisplayVo1 = new TransctFlowGraphicDisplayVo();
      for (int i = 0, length = flowGraphicVoList.size(); i < length; i++)
        flowGraphicDisplayVo1.getNodes().addAll(((TransctFlowGraphicDisplayVo)flowGraphicVoList.get(i)).getNodes()); 
      sortNodesBylevel(flowGraphicDisplayVo1.getNodes(), "desc");
      List<TransctNodeVO> nodeList = new ArrayList<>();
      List<TransctNodeVO> oldNodeList = flowGraphicDisplayVo1.getNodes();
      if (level != -2) {
        for (int j = 0; j < oldNodeList.size(); j++) {
          TransctNodeVO temp = oldNodeList.get(j);
          List<AlarmStatisVO> statisList = temp.getAlarms();
          if (level == -3 && statisList.size() > 0) {
            nodeList.add(temp);
          } else if (level == -1 && statisList.size() == 0) {
            nodeList.add(temp);
          } else {
            for (AlarmStatisVO item : statisList) {
              if (item.getLevel() == level)
                nodeList.add(temp); 
            } 
          } 
        } 
      } else {
        nodeList.addAll(oldNodeList);
      } 
      result.put("total", Integer.valueOf(nodeList.size()));
      if (nodeList.size() > 0) {
        ListPagingOperationUtils<TransctNodeVO> list = new ListPagingOperationUtils(nodeList, page, perPage);
        nodeList = list.getPagedList();
      } 
      flowGraphicDisplayVo1.setNodes(nodeList);
      List<TransctFlowGraphicDisplayVo> flowGraphicVoList1 = new ArrayList<>();
      flowGraphicVoList1.add(flowGraphicDisplayVo1);
      result.put("data", flowGraphicVoList1);
    } 
    return result;
  }
  
  public static int getRowIndex(int pageNum, int pageSize) {
    return (pageNum > 0) ? ((pageNum - 1) * pageSize) : 0;
  }
  
  public static void sortNodesBylevel(List<TransctNodeVO> list, String sortType) {
    if(sortType.equals("desc"))
       Collections.sort(list, Comparator.comparing(TransctNodeVO::getNodeId).reversed());
    else
       Collections.sort(list, Comparator.comparing(TransctNodeVO::getNodeId));
  }
  
  public static void sortAlarmsByLevel(List<AlarmStatisVO> list, String sortType) {
    if(sortType.equals("desc"))
      Collections.sort(list, Comparator.comparing(AlarmStatisVO::getLevel).reversed());
    else
      Collections.sort(list, Comparator.comparing(AlarmStatisVO::getLevel));
  }

  @Override
  public List<TransctFlowGraphicDisplayVo> getFlowGraphicDisplayVoList(String flowId, int alarm, int statis, String a2, long userId) throws Exception {
    List<Long> userIds2 = null;
    if (userId != -1L) {
      userIds2 = new ArrayList<>();
      userIds2.add(Long.valueOf(userId));
    }
    String[] flowIds = flowId.split(",");
    List<String> flowIdList = Arrays.asList(flowIds);
    List<Map<String, Object>> selectFlowsAndNodesByFlowId = this.liveDao.selectFlowsAndNodesByFlowId(flowIdList, userIds2);
    List<Map<String, Object>> flowAndNodeList = (List<Map<String, Object>>)selectFlowsAndNodesByFlowId.get(0);
    List<Map<String, Object>> linkList = this.liveDao.selectLinksByFlowId(flowIdList);
    List<TransctFlowGraphicDisplayVo> flowGraphicVoList = new ArrayList<>();
    handleFlowGraphicDisplayVoList(flowAndNodeList, flowGraphicVoList);
    handleLinks(flowGraphicVoList, linkList);
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList(a2);
    if (alarm == 1)
      setNodeAlarms(flowGraphicVoList, flowId, true, a2, alarmLevelList); 
    return flowGraphicVoList;
  }
  
  private void setNodeAlarms(List<TransctFlowGraphicDisplayVo> flowGraphicVoList, String flowId, boolean needChildrenAlarm, String a2, List<AlarmLevelPO> alarmLevelList) throws Exception{
    setNodeAlarms(flowGraphicVoList, flowId, needChildrenAlarm, a2, alarmLevelList, -1L);
  }

  @Override
  public void setNodeAlarms(List<TransctFlowGraphicDisplayVo> flowGraphicVoList, String flowId, boolean needChildrenAlarm, String a2, List<AlarmLevelPO> alarmLevelList, long userId) throws Exception {
    int timestamp = (int)(System.currentTimeMillis() / 1000L);
    int recoverTime = timestamp - this.recover_time_range;
    JSONArray alarmCountJSONArray = this.alarmShowService.getNodeAlarmCountByFlowId(flowId, recoverTime, userId);
    flowGraphicVoList.forEach(flowGraphicVo -> {
          List<TransctNodeVO> nodes = flowGraphicVo.getNodes();
          nodes.forEach((m)->{
            throw new RuntimeException();
          });
        });
  }
  
  private void setNodeAlarmsV2(List<TransctFlowGraphicDisplayVo> flowGraphicVoList, String flowId, boolean needChildrenAlarm, String a2, List<AlarmLevelPO> alarmLevelList, int level) {
    setNodeAlarmsV2(flowGraphicVoList, flowId, needChildrenAlarm, a2, alarmLevelList, -1L, level);
  }
  
  public void setNodeAlarmsV2(List<TransctFlowGraphicDisplayVo> flowGraphicVoList, String flowId, boolean needChildrenAlarm, String a2, List<AlarmLevelPO> alarmLevelList, long userId, int level) {
    int timestamp = (int)(System.currentTimeMillis() / 1000L);
    int recoverTime = timestamp - this.recover_time_range;
    JSONArray alarmCountJSONArray = this.alarmShowService.getNodeAlarmCountByFlowId(flowId, recoverTime, userId);
    flowGraphicVoList.forEach(flowGraphicVo -> {
          List<TransctNodeVO> nodes = flowGraphicVo.getNodes();
          nodes.forEach((m)->{
            throw new RuntimeException();
          });
    });
  }
  
  public void setNodeAlarms(TransctNodeVO node, JSONObject problemCountJSONObject, JSONObject alarmCountJSONObject, List<AlarmLevelPO> alarmLevelList) {
    String nodeId = node.getNodeId();
    JSONObject problemCount = null;
    JSONObject alarmCount = null;
    if (alarmCountJSONObject.containsKey(nodeId)) {
      problemCount = (JSONObject)alarmCountJSONObject.get(nodeId);
    } else {
      problemCount = null;
      alarmCount = null;
      return;
    } 
    AlarmLevelPO alarmLevelPO = AlarmLevelService.getAlarmLevelInfo(alarmLevelList, problemCount
        .getIntValue("max_level"));
    node.getAlarms().add(getAlarmStatisVO(alarmLevelPO, problemCount));
  }
  
  private JSONObject getNewProblemCount(JSONObject problemCount, JSONObject alarmCount) {
    JSONObject result = new JSONObject();
    int maxLevel1 = problemCount.getIntValue("max_level");
    int maxLevel2 = alarmCount.getIntValue("max_level");
    if (maxLevel1 == maxLevel2) {
      result.put("max_level", Integer.valueOf(maxLevel1));
      result.put("problem_count", Integer.valueOf(Integer.parseInt(problemCount.getOrDefault("problem_count", "0") + "") + 
            Integer.parseInt(alarmCount.getOrDefault("problem_count", "0") + "")));
    } else if (maxLevel1 > maxLevel2) {
      result.put("max_level", Integer.valueOf(maxLevel1));
      result.put("problem_count", Integer.valueOf(Integer.parseInt(problemCount.getOrDefault("problem_count", "0") + "")));
    } else {
      result.put("max_level", Integer.valueOf(maxLevel2));
      result.put("problem_count", Integer.valueOf(Integer.parseInt(alarmCount.getOrDefault("problem_count", "0") + "")));
    } 
    return result;
  }
  
  private AlarmStatisVO getAlarmStatisVO(AlarmLevelPO alarmLevelPO, JSONObject problemCount) {
    AlarmStatisVO result = new AlarmStatisVO();
    result.setAll(problemCount.getOrDefault("problem_count", "0") + "");
    if (alarmLevelPO != null) {
      result.setLevel(alarmLevelPO.getLevel());
      result.setColor(alarmLevelPO.getColor());
    } else {
      result.setLevel(problemCount.getIntValue("max_level"));
      result.setColor("#ffffff");
    } 
    return result;
  }
  
  public boolean setNodeStatis(List<TransctFlowGraphicDisplayVo> flowGraphicVoList, String flowId, String a2, List<AlarmLevelPO> alarmLevelList) throws Exception{
    return setNodeStatis(flowGraphicVoList, flowId, a2, alarmLevelList, -1L, -1L);
  }

  @Override
  public boolean setNodeStatis(List<TransctFlowGraphicDisplayVo> flowGraphicVoList, String flowId, String a2, List<AlarmLevelPO> alarmLevelList, long userId, long getNodeOfUser)  throws Exception{
    Map<String, Boolean> result = new HashMap<>();
    result.put("result", Boolean.valueOf(false));
    JSONArray showedLocalItems = this.itemSelectService.getShowedLocalItemsByFlowId(flowId, userId, getNodeOfUser);
    JSONArray hisAndChangeJSONArray = new JSONArray();
    JSONArray hisStrAndChangeJSONArray = new JSONArray();
    if (CollectionsOperationUtils.isValidCollection((Collection)showedLocalItems)) {
      long startTime = Long.parseLong(DateTimeOperationUtils.getBeforeOrAfterDateTime(
            DateTimeOperationUtils.format(new Date(), "yyyyMMddHHmmss"), "yyyyMMddHHmmss", 13, -1 * this.get_item_value_frequency));
      hisAndChangeJSONArray = this.hisService.getHisAndChangeByItemId((List)showedLocalItems, "his", 1, startTime);
      hisStrAndChangeJSONArray = this.hisService.getHisAndChangeByItemId((List)showedLocalItems, "his_str", 0, startTime);
    } 
    JSONObject hisAndChangeJSONObject = FastJsonOperationUtils.JSONArrayToJSONObejct(hisAndChangeJSONArray, "item_id", false);
    JSONObject hisStrAndChangeJSONObject = FastJsonOperationUtils.JSONArrayToJSONObejct(hisStrAndChangeJSONArray, "item_id", false);
    JSONObject itemInfosJSONObject = null;
    flowGraphicVoList.forEach(flowGraphicVo -> {
          List<TransctNodeVO> nodes = flowGraphicVo.getNodes();
          if (!CollectionsOperationUtils.isValidCollection(nodes))
            return;
        try {
          Map<String, TransctNodeVO> nodeMap = CollectionsOperationUtils.listToMap(nodes, "nodeId", new HashMap<>());
          if (!MapOperationUtils.isValidMap(nodeMap))
            return;
          JSONObject showedLocalItem = null;
          JSONObject hisAndChange = null;
          TransctNodeVO node2 = null;
          for (Object obj : showedLocalItems) {
            showedLocalItem = (JSONObject)obj;
            String itemId = showedLocalItem.getString("item_id");
            if (hisAndChangeJSONObject.containsKey(itemId)) {
              hisAndChange = (JSONObject)hisAndChangeJSONObject.get(itemId);
            } else if (hisStrAndChangeJSONObject.containsKey(itemId)) {
              hisAndChange = (JSONObject)hisStrAndChangeJSONObject.get(itemId);
            } else {
              hisAndChange = null;
            }
            String nodeId = showedLocalItem.getString("node_id");
            if (!nodeMap.containsKey(nodeId))
              continue;
            node2 = nodeMap.get(nodeId);
            if (hisAndChange != null) {
              AlarmLevelPO alarmLevelPO = AlarmLevelService.getAlarmLevelInfo(alarmLevelList, hisAndChange.getIntValue("alarm_level"));
              node2.getStatis().add(getItemStatisVO(showedLocalItem, hisAndChange, itemInfosJSONObject, alarmLevelPO));
              result.put("result", Boolean.valueOf(true));
            }
          }
          nodes = MapOperationUtils.getMapValForList(nodeMap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        });
    return ((Boolean)result.get("result")).booleanValue();
  }
  
  private ItemStatisVO getItemStatisVO(JSONObject showedItemAndTrigger, JSONObject historyAndChange, JSONObject itemInfosJSONObject, AlarmLevelPO alarmLevelPO) throws Exception {
    ItemStatisVO result = new ItemStatisVO();
    result.setName(showedItemAndTrigger.getOrDefault("item_name", "") + "");
    if (alarmLevelPO != null) {
      result.setColor(alarmLevelPO.getColor());
    } else {
      result.setColor("#ffffff");
    } 
    String add = "0";
    String all = this.show_default_value;
    if (historyAndChange != null)
      if ("0".equals(showedItemAndTrigger.getString("value_type"))) {
        add = MathOperationUtils.round(historyAndChange.getOrDefault("change_value", "0") + "", this.item_value_decimal);
        add = StringOperationUtils.rvZeroAndDot(add);
        all = MathOperationUtils.round(historyAndChange.getOrDefault("value", "0") + "", this.item_value_decimal);
        all = StringOperationUtils.rvZeroAndDot(all);
        try {
          if ("B".equals(showedItemAndTrigger.getOrDefault("units", "") + "")) {
            Map<String, String> tranferedFileSize = FileOperationUtils.tranferFileSize2(Long.parseLong(all));
            all = tranferedFileSize.get("value");
            showedItemAndTrigger.put("units", tranferedFileSize.get("units"));
          } 
        } catch (Exception e) {
           throw e;
        } 
      } else {
        add = historyAndChange.getString("change_value");
        all = historyAndChange.getString("value");
      }  
    if (StringOperationUtils.isValidStr2(all)) {
      if (showedItemAndTrigger.getOrDefault("key", "").equals("ping.host")) {
        try {
          if (Integer.parseInt(all) <= 0) {
            all = "无响应";
          } else if (Integer.parseInt(all) >= 100) {
            all = "正常";
          } else {
            all = "丢包";
          } 
        } catch (Exception e) {
          throw e;
        } 
        result.setUnits("");
      } else if ((showedItemAndTrigger.getOrDefault("key", "") + "").equals("agent.ping")) {
        try {
          if (Integer.parseInt(all) == 0) {
            all = "无响应";
          } else if (Integer.parseInt(all) == 1) {
            all = "正常";
          } else {
            all = this.show_default_value;
          } 
        } catch (Exception e) {
          throw e;
        } 
        result.setUnits("");
      } else if ((showedItemAndTrigger.getOrDefault("key", "") + "").contains("net.tcp.service")) {
        try {
          if (Integer.parseInt(all) == 0) {
            all = "无响应";
          } else if (Integer.parseInt(all) == 1) {
            all = "正常";
          } else {
            all = this.show_default_value;
          } 
        } catch (Exception e) {
          throw e;
        } 
        result.setUnits("");
      } else {
        result.setUnits(showedItemAndTrigger.getOrDefault("units", "") + "");
      } 
    } else {
      result.setUnits("");
    } 
    result.setAll(all);
    result.setAdd(StringOperationUtils.getChangeValue(add));
    return result;
  }
  
  public TransctNodeVO parseMapToNodeVO(Map<String, Object> map) {
    TransctNodeVO nodeVO = new TransctNodeVO();
    nodeVO.setNodeId(map.get("node_id").toString());
    nodeVO.setNodeTypeId(Integer.parseInt(map.get("node_type_id").toString()));
    nodeVO.setNodeName((map.get("nodeName") == null) ? "" : map.get("nodeName").toString());
    nodeVO.setParentNodeId((map.get("parentNodeId") == null) ? "" : map.get("parentNodeId").toString());
    nodeVO.setNickName((map.get("nick_name") == null) ? "" : map.get("nick_name").toString());
    nodeVO.setIp(IpUtils.long2Ip(((Long)map.get("ip")).longValue()));
    nodeVO.setAreaCode((map.get("area_code") == null) ? "" : map.get("area_code").toString());
    nodeVO.setPort((map.get("port") == null) ? 0 : Integer.parseInt(map.get("port").toString()));
    nodeVO.setCity((map.get("city") == null) ? "" : map.get("city").toString());
    nodeVO.setProv((map.get("prov") == null) ? "" : map.get("prov").toString());
    nodeVO.setZbxHostId((map.get("zbx_host_id") == null) ? null : Long.valueOf(Long.parseLong(map.get("zbx_host_id").toString())));
    nodeVO.setDescpt((map.get("nodeDescpt") == null) ? "" : map.get("nodeDescpt").toString());
    nodeVO.setStationTypeId((map.get("station_type_id") == null) ? 0 : Integer.parseInt(map.get("station_type_id").toString()));
    nodeVO.setStationName((map.get("station_name") == null) ? "" : map.get("station_name").toString());
    nodeVO.setProvCode(handleProvCode(nodeVO.getAreaCode()));
    nodeVO.setXy(handleXY(map.get("xy")));
    nodeVO.setPos(handleXY(map.get("pos")));
    nodeVO.setObject_id(map.get("object_id").toString());
    nodeVO.setIsItemShowed(Integer.parseInt(map.get("isItemShowed").toString()));
    return nodeVO;
  }
  
  public TransctLinkVO parseLinkVO(Map<String, Object> link) {
    TransctLinkVO linkVO = new TransctLinkVO();
    linkVO.setLinkId(link.get("link_id").toString());
    linkVO.setBegin(link.get("start_node_id").toString());
    linkVO.setEnd(link.get("end_node_id").toString());
    linkVO.setXy(handleXY(link.get("xy")));
    linkVO.setPos(handleXY(link.get("pos")));
    return linkVO;
  }
  
  public void handleChildNodeVO(TransctNodeVO nodeVO, List<Map<String, Object>> flowAndNodeList) {
    flowAndNodeList.forEach(node -> {
          if (node.get("node_id") != null && node.get("parentNodeId") != null && !node.get("node_id").toString().equals(node.get("parentNodeId").toString()))
            if (nodeVO.getNodeId().equals(node.get("parentNodeId").toString())) {
              TransctNodeVO childNodeVO = parseMapToNodeVO(node);
              if (nodeVO.getNodeTypeId() == this.VIRTUALSTATION) {
                if (nodeVO.getChildren().size() < 6) {
                  nodeVO.getChildren().add(childNodeVO);
                  handleChildNodeVO(childNodeVO, flowAndNodeList);
                } 
              } else {
                nodeVO.getChildren().add(childNodeVO);
                handleChildNodeVO(childNodeVO, flowAndNodeList);
              } 
            }  
        });
  }
  
  public int[] handleXY(Object xy) {
    if (Objects.isNull(xy) || "".equals(xy.toString()))
      return new int[0]; 
    String[] xyStr = xy.toString().split(",");
    int[] xys = new int[xyStr.length];
    for (int i = 0; i < xyStr.length; i++)
      xys[i] = Integer.parseInt(xyStr[i]); 
    return xys;
  }
  
  public String handleProvCode(String areaCode) {
    String provCode = "";
    if (!StringUtils.isEmpty(areaCode))
      provCode = areaCode.substring(0, 2) + "0000"; 
    return provCode;
  }
  
  public void handleFlowGraphicDisplayVoList(List<Map<String, Object>> flowAndNodeList, List<TransctFlowGraphicDisplayVo> flowGraphicVoList) {
    flowAndNodeList.forEach(map -> {
          TransctFlowGraphicDisplayVo flowGraphicDisplayVo = null;
          for (TransctFlowGraphicDisplayVo flowGraphicDisplayVo2 : flowGraphicVoList) {
            if (flowGraphicDisplayVo2.getFlowId().equals(map.get("flow_id").toString())) {
              flowGraphicDisplayVo = flowGraphicDisplayVo2;
              break;
            } 
          } 
          if (Objects.isNull(flowGraphicDisplayVo)) {
            flowGraphicDisplayVo = new TransctFlowGraphicDisplayVo();
            flowGraphicDisplayVo.setFlowId(map.get("flow_id").toString());
            flowGraphicDisplayVo.setName((map.get("name") != null) ? map.get("name").toString() : "");
            flowGraphicDisplayVo.setDataTypeId(Long.parseLong(map.get("data_type_id").toString()));
            flowGraphicDisplayVo.setBoardType((map.get("board_type") != null) ? map.get("board_type").toString() : "");
            flowGraphicDisplayVo.setDescpt((map.get("descpt") != null) ? map.get("descpt").toString() : "");
            flowGraphicDisplayVo.setNodexIndex(Long.parseLong(map.get("nodex_index").toString()));
            flowGraphicDisplayVo.setMaxX(Integer.parseInt(map.get("maxX").toString()));
            flowGraphicDisplayVo.setMaxY(Integer.parseInt(map.get("maxY").toString()));
            flowGraphicVoList.add(flowGraphicDisplayVo);
          } 
          if (map.get("node_id") != null && map.get("parentNodeId") != null && map.get("node_id").toString().equals(map.get("parentNodeId").toString())) {
            TransctNodeVO nodeVO = parseMapToNodeVO(map);
            handleChildNodeVO(nodeVO, flowAndNodeList);
            flowGraphicDisplayVo.getNodes().add(nodeVO);
          } 
        });
  }
  
  public void handleFlowGraphicDisplayVoListNew(List<Map<String, Object>> flowAndNodeList, List<TransctFlowGraphicDisplayVo> flowGraphicVoList, int nodeTypeId, List<Map<String, Object>> selectAllFlowsAndNodesByFlowId) {
    flowAndNodeList.forEach(map -> {
          TransctFlowGraphicDisplayVo flowGraphicDisplayVo = null;
          for (TransctFlowGraphicDisplayVo flowGraphicDisplayVo2 : flowGraphicVoList) {
            if (flowGraphicDisplayVo2.getFlowId().equals(map.get("flow_id").toString())) {
              flowGraphicDisplayVo = flowGraphicDisplayVo2;
              break;
            } 
          } 
          if (Objects.isNull(flowGraphicDisplayVo)) {
            flowGraphicDisplayVo = new TransctFlowGraphicDisplayVo();
            flowGraphicDisplayVo.setFlowId(map.get("flow_id").toString());
            flowGraphicDisplayVo.setName((map.get("name") != null) ? map.get("name").toString() : "");
            flowGraphicDisplayVo.setDataTypeId(Long.parseLong(map.get("data_type_id").toString()));
            flowGraphicDisplayVo.setBoardType((map.get("board_type") != null) ? map.get("board_type").toString() : "");
            flowGraphicDisplayVo.setDescpt((map.get("descpt") != null) ? map.get("descpt").toString() : "");
            flowGraphicDisplayVo.setNodexIndex(Long.parseLong(map.get("nodex_index").toString()));
            flowGraphicVoList.add(flowGraphicDisplayVo);
          } 
          if (map.get("node_id") != null && map.get("parentNodeId") != null && nodeTypeId == Integer.parseInt(map.get("node_type_id").toString())) {
            TransctNodeVO nodeVO = parseMapToNodeVO(map);
            handleChildNodeVO(nodeVO, selectAllFlowsAndNodesByFlowId);
            flowGraphicDisplayVo.getNodes().add(nodeVO);
          } 
        });
  }
  
  public void handleLinks(List<TransctFlowGraphicDisplayVo> flowGraphicVoList, List<Map<String, Object>> linkList) {
    flowGraphicVoList.forEach(flowGraphicDisplayVo2 -> linkList.forEach((map)->{

    }));
  }

  @Override
  public int updateFlowEditStatus(String flowId, int editStatus) throws Exception {
    return this.flowDao.updateFlowEditStatus(flowId, editStatus);
  }

}
